<template>
	<div class="bg">
		<goback title="站点管理页"></goback>
		
		
		<div class="map-container">
			<baidu-map class="map" ref="map" :zoom="zoom" :min-zoom="minzoom" :max-zoom="maxzoom"
				:scroll-wheel-zoom="true" :center="center" @ready="handleMapReady">
				<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true"
					:autoLocation="true"></bm-geolocation>
				<!-- 新增标记点 -->
				<bm-control class="map-controls">
					<button @click="toggleAddMarkerMode" class="btn">{{ addingMarker ? '取消添加标记点' : '新增标记点' }}</button>
				</bm-control>
				<bm-marker v-for="(marker, index) in markers" :position="{lng: marker.lng,lat: marker.lat}"
					:key="index">
				</bm-marker>
			</baidu-map>
		</div>
		<div class="marker-list">
			<div class="card">
				<h3 class="card_title">站点说明</h3>
				<div class="card_context">
					<div>在此设置企业的回收仓库,我们支持一企多仓,不同的仓库定义存储不同的秸秆~</div>
				</div>
			</div>
			<div class="card">
				<h3 class="card_title">站点列表</h3>
				<ul class="marker-list-ul">
					<li v-for="(marker, index) in markers" :key="index" class="address-list card">
						<div class="name-label">
							<div>
								{{ marker.name }}
								<button @click="editMarker(marker)" class="btn btn-edit">编辑</button>
							</div>
							<div v-if="marker.distance !== null" style="margin-bottom: 10px;">距离您所在的位置
								{{ marker.distance }}
								公里
							</div>
							<!-- 显示逆地址解析的结果 -->
							<div> {{ marker.address }}</div>
						</div>
						<div class="btn-box">
							<button @click="moveToMarker(marker)" class="btn btn-move">传送至该地</button>
							<button @click="removeMarker(index)" class="btn btn-danger">删除标记点</button>
						</div>

					</li>
				</ul>
				<button class="save_btn" @click="sendData">确认保存</button>
			</div>
		</div>
		<div v-if="showEditForm" class="edit-form">
			<form @submit.prevent="saveEditedMarker" class="form">
				<div class="form-group">
					<label>站点名称:</label>
					<input type="text" v-model="editedMarker.name" class="form-control">
				</div>
				<button type="submit" class="btn btn-primary">保存</button>
			</form>

		</div>

		

	</div>
</template>

<script>
	import BaiduMap from 'vue-baidu-map/components/map/Map.vue';
	import axios from 'axios';


	export default {
		name: "daohang",
		components: {
			BaiduMap,
		},
		data() {
			return {
				map: {},
				BMap: {},
				zoom: 15,
				minzoom: 1,
				maxzoom: 100,
				center: {
					lng: "",
					lat: ""
				},
				markers: [],
				addingMarker: false,
				showEditForm: false,
				editedMarker: null,
			};
		},
		mounted() {
			this.getData();
			this.updateDistances();
		},
		methods: {
			handleMapReady({
				BMap,
				map
			}) {
				this.BMap = BMap;
				this.map = map;
				this.map.addEventListener('click', this.handleMapClick);

				var that = this;
				let geolocation = new BMap.Geolocation();
				geolocation.getCurrentPosition(function(e) {
					if (this.getStatus() == BMAP_STATUS_SUCCESS) {
						let point = new BMap.Point(e.point.lng, e.point.lat);
						that.map.setCenter(point);
						that.center = {
							lng: e.point.lng,
							lat: e.point.lat
						}

						that.updateDistances(); // 更新标记点距离中心点的距离
						// 添加下面这行代码来手动更新地图的中心点
						that.map.setCenter(new that.BMap.Point(that.center.lng, that.center.lat));


					}
				})

				this.map.enableScrollWheelZoom(true)
				this.map.enableDoubleClickZoom(true)
				map.setMapStyle({

					style: [{
						"featureType": "water",
						"elementType": "geometry.fill",
						"stylers": {
							"color": "#ff0000ff",
							"hue": "#ff0000",
							"weight": "1",
							"lightness": 1,
							"saturation": 100,
							"visibility": "on"
						}
					}]

				})



			},
			handleMapClick(event) {
				let that = this;
				if (this.addingMarker) {
					const point = event.point;
					console.log(point);

					// 创建地理编码器实例
					const geoc = new this.BMap.Geocoder();
					// 将经纬度坐标转换为地理位置描述
					geoc.getLocation(new this.BMap.Point(point.lng, point.lat), (result) => {
						
						let address = result.address;
						// result中包含了逆地址解析的结果
						if (result.surroundingPois.length == 0) {
							// const address = result.address;
						} else {
							address = address + result.surroundingPois[0].title;
						}

						const newMarker = {
							id: that.markers.length,
							lng: point.lng,
							lat: point.lat,
							name: '站点' + (that.markers.length + 1),
							address: address,
							distance: this.calculateDistance(point, that.center)
						};
						that.markers.push(newMarker);
						this.addingMarker = !this.addingMarker;
						if (!this.addingMarker) {
							this.showEditForm = false;
							this.editedMarker = null;
						}
					});


				}
			},
			// toggleAddMarkerMode() {
			// 	this.addingMarker = !this.addingMarker;
			// },
			toggleAddMarkerMode() {
				this.addingMarker = !this.addingMarker;
				// 如果取消添加标记点，重置编辑表单状态
				if (!this.addingMarker) {
					this.showEditForm = false;
					this.editedMarker = null;
				}
			},
			// 逆地址解析
			reverseGeocoding(position) {

				// 创建地理编码器实例
				const geoc = new this.BMap.Geocoder();
				// 将经纬度坐标转换为地理位置描述
				geoc.getLocation(new this.BMap.Point(position.lng, position.lat), (result) => {
					// result中包含了逆地址解析的结果
					const address = result.address + result.surroundingPois[0].title;
					console.log('逆地址解析结果：', address);
					// 将解析结果保存到标记点对象中
					this.markers[this.markers.length - 1].address = address;
				});


			},

			calculateDistance(point1, point2) {
				const rad = Math.PI / 180;
				const lat1 = point1.lat * rad;
				const lat2 = point2.lat * rad;
				const deltaLng = (point1.lng - point2.lng) * rad;
				const R = 6371; // 地球半径，单位为千米
				const distance = (Math.round(R * Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(
					lat2) * Math.cos(deltaLng)) * 1000) / 1000).toFixed(2);
				return distance;
			},
			updateDistances() {
				this.markers.forEach(marker => {
					marker.distance = this.calculateDistance({
						lat: marker.lat,
						lng: marker.lng
					}, this.center);
				});
			},
			moveToMarker(marker) {
				this.center = {
					lat: marker.lat,
					lng: marker.lng
				};
			},
			removeMarker(index) {
				this.markers.splice(index, 1);
				this.sendData();
			},
			editMarker(marker) {
				this.showEditForm = true;
				this.editedMarker = marker;
			},
			saveEditedMarker() {
				this.showEditForm = false;
				this.editedMarker = null;
			},

			sendData() {
				this.axios.post(`${this.IP}/set_stations`, {
					token: this.getStorage("token"),
					jsonArray: this.markers
				}).then(res => {
					console.log(this.markers);
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;
			},
			getData() {
				this.axios.get(`${this.IP}/get_stations`, {
					params: {
						token: this.getStorage("token"),
					}
				}).then(res => {
					this.markers = res.data;
					console.log(this.markers);
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;
			},


		},
	};
</script>

<style scoped>
	.goback {
		position: fixed;
		width: 100vw;

	}

	.map-container {
		position: relative;
		height: calc(100vh-54vw);
		width: 100vw;

		/* 计算地图和标记点列表区域的高度 */
	}

	.map {
		position: fixed;
		top: 15vw;
		width: 100vw;
		height: 54vw;
	}

	.map-controls {
		position: absolute;
		bottom: 20px;
		left: 200px;
		z-index: 13;
	}

	.marker-list {
		position: fixed;
		top: 70vw;
		/* 与地图底部对齐 */
		bottom: 0;
		width: 100%;
		padding-bottom: 14vw;
		overflow-y: auto;
		/* 在内容溢出时显示滚动条 */
	}

	.marker-list h3 {
		margin-bottom: 10px;
		margin-left: 4vw;
		font-size: 1.2em;
	}

	.marker-list-ul {
		display: flex;
		flex-direction: column;
		align-items: center;
		list-style: none;
		padding: 0;
	}

	.marker-list-ul li {
		border-bottom: 1px solid #e3e3e3;
		padding: 1vw;
	}

	.address-list {
		width: 94%;
		height: 25vw;
		background-color: #eee;
		display: flex;
		align-items: center;
		margin-top: 10px;
		border-radius: 2vw;
	}

	.name-label {
		width: 80%;
		height: 13vh;
		border-right: 1px solid #aaaa00;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		padding-left: 50px;

	}



	.btn {
		background-color: #007bff;
		color: #fff;
		border: none;
		border-radius: 4px;
		padding: 8px 12px;
		margin-right: 10px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.btn-edit {
		margin: 10px;
	}

	.btn-box {
		width: 40%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-left: 20px;
	}

	.btn:hover {
		background-color: #0056b3;
	}

	.btn-move {
		width: 80%;
	}

	.btn-danger {
		width: 80%;
		margin-top: 20px;
		background-color: #dc3545;
	}

	.btn-danger:hover {
		background-color: #c82333;
	}

	.btn-edit {
		background-color: #28a745;
	}

	.btn-edit:hover {
		background-color: #218838;
	}

	.edit-form {
		width: 60%;
		height: 30%;
		position: absolute;
		top: 1vw;
		right: 1vw;
		background-color: #fff;
		padding: 20px;
		border: 1px solid #ccc;
		border-radius: 4px;
		z-index: 999;
	}

	.form-group {
		position: relative;
		margin-bottom: 15px;
	}

	.form-control {
		width: 100%;
		padding: 8px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	.btn-primary {
		position: absolute;
		right: 1vw;
		bottom: 1.5vw;
		background-color: #007bff;
		color: #fff;
		border: none;
		border-radius: 4px;
		padding: 8px 12px;
		cursor: pointer;
	}

	.btn-primary:hover {
		background-color: #0056b3;
	}

	.save_btn {
		display: block;
		width: 96%;
		text-align: center;
		padding: 2vw;
		border-radius: 30px;
		margin: 0 auto;
		background: linear-gradient(to right, white, #f0f0f0);
		transition: background 0.3s ease;
		cursor: pointer;
		text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
		/* 添加文字阴影 */
		color: #333;
		font-weight: bold;
		font-size: 32px;
	}

	.save_btn:hover {
		color: #28a745;
	}
</style>